package com.heima.article.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 文章业务
 * @author Mr.Chen
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    /*    @Value("${fileServerUrl}")
    private String fileServerUrl;*/

    @Resource
    private ApArticleMapper apArticleMapper;


    /**
     *单页最大加载的数字
     */
    private final static short MAX_PAGE_SIZE = 50;

    /**
     * 根据参数加载文章列表
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto dto
     * @return 返回
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //1.判断dto
        if(dto==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断size
        Integer size = dto.getSize();
        if(size==null || size==0){
            size=10;
        }
        dto.setSize(Math.min(size,MAX_PAGE_SIZE));
        //3、加载方式判断
        if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)&&!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //4、tag判断 文章频道校验
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //5、时间
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        //查询数据
        List<ApArticle> apArticleList = apArticleMapper.loadArticleList(dto, loadtype);
        //封装数据
        ResponseResult responseResult = ResponseResult.okResult(apArticleList);
      //  responseResult.setHost(fileServerUrl);
        return responseResult;
    }
}